using AbpMvc.Demo.Products;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace AbpMvc.Demo.Web.Pages.Products
{
    public class EditProductModalModel : DemoPageModel
    {
        [HiddenInput]
        [BindProperty(SupportsGet =true)]
        public Guid Id { get; set; }

        [BindProperty]
        public CreateEditProductViewModel Product { get; set; }

        public SelectListItem[] Categories { get; set; }

        private readonly IProductService productService;

        public EditProductModalModel(IProductService productService)
        {
            this.productService = productService;
        }


        public async Task OnGetAsync()
        {
            var productDto = await productService.GetAsync(Id);
            Product = ObjectMapper.Map<ProductDto, CreateEditProductViewModel>(productDto);
            var categoryLookup = await productService.GetCategoriesAsync();
            Categories = categoryLookup.Items.Select(p => new SelectListItem(p.Name, p.Id.ToString())).ToArray();
        }
        public async Task<IActionResult> OnPostAsync()
        {
            await productService.UpdateAsync(Id, ObjectMapper.Map<CreateEditProductViewModel, CreateOrUpdateProductDto>(Product));
            return NoContent();
        }
    }
}
